package com.ukefu.webim.util;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.ModelMap;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.DicSegment;
import com.ukefu.util.es.SearchTools;
import com.ukefu.webim.service.es.VoiceTranscriptionRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.repository.AgentServiceRepository;
import com.ukefu.webim.service.repository.CallOutRoleRepository;
import com.ukefu.webim.service.repository.JobDetailRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.QualityFormFilterItemRepository;
import com.ukefu.webim.service.repository.QualityFormFilterRepository;
import com.ukefu.webim.service.repository.QualityMissionHisRepository;
import com.ukefu.webim.service.repository.QualityResultItemRepository;
import com.ukefu.webim.service.repository.QualityResultRepository;
import com.ukefu.webim.service.repository.QualityTemplateItemRepository;
import com.ukefu.webim.service.repository.QualityTemplateRepository;
import com.ukefu.webim.service.repository.StatusEventRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.service.repository.UserRoleRepository;
import com.ukefu.webim.web.model.AgentService;
import com.ukefu.webim.web.model.JobDetail;
import com.ukefu.webim.web.model.QualityFormFilter;
import com.ukefu.webim.web.model.QualityFormFilterItem;
import com.ukefu.webim.web.model.QualityMissionHis;
import com.ukefu.webim.web.model.QualityResult;
import com.ukefu.webim.web.model.QualityResultItem;
import com.ukefu.webim.web.model.QualityTemplate;
import com.ukefu.webim.web.model.QualityTemplateItem;
import com.ukefu.webim.web.model.StatusEvent;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.VoiceTranscription;
import com.ukefu.webim.web.model.WorkOrders;

/**
 * 	质检 -	公共 工具类
 *
 */
public class QualityDataUtils {
	
	/**
	 * 我的部门以及授权给我的部门 - 筛选表单
	 * @param filterRes
	 * @param userRoleRes
	 * @param callOutRoleRes
	 * @param user
	 * @return
	 */
	public static List<QualityFormFilter> getFormFilterList(QualityFormFilterRepository filterRes,UserRoleRepository userRoleRes , CallOutRoleRepository callOutRoleRes, final User user){
		
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		
		List<QualityFormFilter> formFilterList = filterRes.findAll(new Specification<QualityFormFilter>(){
			@Override
			public Predicate toPredicate(Root<QualityFormFilter> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				
				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));
				
				if(organList.size() > 0){
					
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(in) ;
				
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}});
		
		return formFilterList;
	}
	
	/**
	 * 	质检数据 - 回收到池子
	 * @param dataid
	 * @param type
	 * @param orgi
	 */
	public static void Recycle(String dataid, String type, String orgi, String recyctype) {
		
		StatusEventRepository statusEventRes = UKDataContext.getContext().getBean(StatusEventRepository.class);
		WorkOrdersRepository workOrdersRes = UKDataContext.getContext().getBean(WorkOrdersRepository.class);
		AgentServiceRepository agentServiceRes = UKDataContext.getContext().getBean(AgentServiceRepository.class);
		QualityMissionHisRepository qcMissionRes = UKDataContext.getContext().getBean(QualityMissionHisRepository.class);
		QualityResultRepository qcResultRes = UKDataContext.getContext().getBean(QualityResultRepository.class);
		QualityResultItemRepository qcResultItemRes = UKDataContext.getContext().getBean(QualityResultItemRepository.class);
		String data = null;
		if(type.equals(UKDataContext.QcFormFilterTypeEnum.CALLEVENT.toString())) {
			StatusEvent statusEvent = statusEventRes.findById(dataid);
			if(statusEvent != null) {
				statusEvent.setQualitydistime(null);
				statusEvent.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					statusEvent.setQualitydisorgan(null);
					statusEvent.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					statusEvent.setQualityactid(null);
					statusEvent.setQualityfilterid(null);
					statusEvent.setAssuser(null);
					statusEvent.setQualitytype(null);
					
				}else {
					statusEvent.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
				}
				statusEvent.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				statusEvent.setQualityorgan(null);
				statusEvent.setQualityscore(0);
				statusEvent.setQualitytime(null);
				statusEvent.setQualityuser(null);
				statusEventRes.save(statusEvent);
				data = statusEvent.getId();
			}
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.WORKORDERS.toString())) {
			WorkOrders workOrders = workOrdersRes.getByIdAndOrgi(dataid, orgi);
			if(workOrders != null) {
				workOrders.setQualitydistime(null);
				workOrders.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					workOrders.setQualitydisorgan(null);
					workOrders.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					workOrders.setQualityactid(null);
					workOrders.setQualityfilterid(null);
					workOrders.setAssuser(null);
					
				}else {
					workOrders.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
					workOrders.setQualitytype(null);
				}
				workOrders.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				workOrders.setQualityorgan(null);
				workOrders.setQualityscore(0);
				workOrders.setQualitytime(null);
				workOrders.setQualityuser(null);
				workOrdersRes.save(workOrders);
				data = workOrders.getId();
			}
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.AGENTSERVICE.toString())) {
			AgentService agentService = agentServiceRes.findByIdAndOrgi(dataid, orgi);
			if(agentService != null) {
				agentService.setQualitydistime(null);
				agentService.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					agentService.setQualitydisorgan(null);
					agentService.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					agentService.setQualityactid(null);
					agentService.setQualityfilterid(null);
					agentService.setAssuser(null);
					
					agentService.setQualitytype(null);
				}else {
					agentService.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
				}
				agentService.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				agentService.setQualityorgan(null);
				agentService.setQualityscore(0);
				agentService.setQualitytime(null);
				agentService.setQualityuser(null);
				agentServiceRes.save(agentService);
				data = agentService.getId();
			}
		}
		if(data != null) {
			List<QualityMissionHis> missionList = qcMissionRes.findByDataidAndOrgi(data, orgi);
			if(missionList.size() > 0) {
				/*QualityActivityTask task = qcTaskRes.findByIdAndOrgi(missionList.get(0).getTaskid(), orgi);
				if(task != null) {
					if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
						task.setRenum(task.getRenum() + 1);//回收到池子数
					}else {
						task.setReorgannum(task.getReorgannum() + 1);//回收到部门数
						task.setNotassigned(task.getNotassigned() + 1);//未分配数
					}
					qcTaskRes.save(task);
				}*/
				qcMissionRes.delete(missionList);
			}
			QualityResult qualityResult = qcResultRes.findByDataidAndOrgi(data, orgi) ;
			if (qualityResult!=null) {
				List<QualityResultItem> qualityResultItemList = qcResultItemRes.findByResultidAndOrgi(qualityResult.getId(), orgi) ;
				if (qualityResultItemList!=null && qualityResultItemList.size()>0) {
					qcResultItemRes.delete(qualityResultItemList);
				}
				qcResultRes.delete(qualityResult);
			}
			
		}
	}
	/**
	 * 搜索条件
	 */
	public static void searchCondition(ModelMap map ,HttpServletRequest request,final User user) {
		
		JobDetailRepository qcActivityRes = UKDataContext.getContext().getBean(JobDetailRepository.class);
		OrganRepository organRes = UKDataContext.getContext().getBean(OrganRepository.class);
		QualityFormFilterRepository qcFormFilterRes = UKDataContext.getContext().getBean(QualityFormFilterRepository.class);
		
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		map.addAttribute("organList", organRes.findAll(organList));
		map.put("activityList", qcActivityRes.findAll(new Specification<JobDetail>(){
			@Override
			public Predicate toPredicate(Root<JobDetail> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				list.add(cb.equal(root.get("tasktype").as(String.class), UKDataContext.TaskType.QUALITY.toString()));

				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));

				if(organList.size() > 0){
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}	
				list.add(in) ;
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}}));
		map.put("formFilterList", qcFormFilterRes.findAll(new Specification<QualityFormFilter>(){
			@Override
			public Predicate toPredicate(Root<QualityFormFilter> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				
				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));
				
				if(organList.size() > 0){
					
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(in) ;
				
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}}));
		map.put("allUserList",UKDataContext.getContext().getBean(UserRepository.class).findByOrgiAndDatastatus(user.getOrgi(), false));
	}
	
	public static BoolQueryBuilder searchWorkordersCon(ModelMap map ,HttpServletRequest request) {
		BoolQueryBuilder bool = new BoolQueryBuilder();
		//搜索框
		if(!StringUtils.isBlank(request.getParameter("q"))) {
			String q = request.getParameter("q") ;
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			if(!StringUtils.isBlank(q)){
				bool.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
				map.put("q", q) ;
			}
		}
		if(!StringUtils.isBlank(request.getParameter("qualityfilterid"))) {
			bool.must(termQuery("qualityfilterid", request.getParameter("qualityfilterid"))) ;
			map.put("qualityfilterid", request.getParameter("qualityfilterid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisuser"))) {
			bool.must(termQuery("qualitydisuser", request.getParameter("qualitydisuser"))) ;
			map.put("qualitydisuser", request.getParameter("qualitydisuser")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualityactid"))) {
			bool.must(termQuery("qualityactid", request.getParameter("qualityactid"))) ;
			map.put("qualityactid", request.getParameter("qualityactid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydistype"))) {
			bool.must(termQuery("qualitydistype", request.getParameter("qualitydistype"))) ;
			map.put("qualitydistype", request.getParameter("qualitydistype")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisorgan"))) {
			bool.must(termQuery("qualitydisorgan", request.getParameter("qualitydisorgan"))) ;
			map.put("qualitydisorgan", request.getParameter("qualitydisorgan")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitystatus"))) {
			bool.must(termQuery("qualitystatus", request.getParameter("qualitystatus"))) ;
			map.put("qualitystatus", request.getParameter("qualitystatus")) ;
		}
		RangeQueryBuilder rangeQuery = null ;
		if(!StringUtils.isBlank(request.getParameter("begin")) || !StringUtils.isBlank(request.getParameter("end"))){
			if(!StringUtils.isBlank(request.getParameter("begin"))) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("qualitydistime").from(UKTools.dateFormate.parse(request.getParameter("begin")).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(request.getParameter("end")) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("qualitydistime").to(UKTools.dateFormate.parse(request.getParameter("end")).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(request.getParameter("end")).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("begin", request.getParameter("begin")) ;
			map.put("end", request.getParameter("end")) ;
		}
		if(rangeQuery != null) {
			bool.must(rangeQuery);
		}
		return bool;
	}
	
	public static int getNameNum(ModelMap map, String type, JobDetail act, User user) {
		
		QualityFormFilterItemRepository qcFormFilterRes = UKDataContext.getContext().getBean(QualityFormFilterItemRepository.class);		
		List<QualityFormFilterItem> qcFormFilterItemList = qcFormFilterRes.findByOrgiAndQcformfilterid(act.getOrgi(), act.getFilterid());
		int allsum = 0;
		if(type.equals(UKDataContext.QcFormFilterTypeEnum.CALLEVENT.toString())) {
			List<StatusEvent> callList = SearchTools.searchQualityStatusEvent(act.getOrgi(), qcFormFilterItemList, user);
			allsum = callList.size();
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.WORKORDERS.toString())) {
			List<WorkOrders> workList = SearchTools.searchQualityWorkOrders(act.getOrgi(), qcFormFilterItemList, user);
			allsum = workList.size();
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.AGENTSERVICE.toString())) {
			List<AgentService> agentList = SearchTools.searchQualityAgentService(act.getOrgi(), qcFormFilterItemList, user);
			allsum = agentList.size();
		}
		map.addAttribute("allsum", allsum);
		return allsum;
	}
	
	public static List<StatusEvent> getOrganDisnotCallevent(User user){
		final String orgi = user.getOrgi();
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		StatusEventRepository statusEventRes = UKDataContext.getContext().getBean(StatusEventRepository.class);
		List<StatusEvent> list = statusEventRes.findAll(new Specification<StatusEvent>(){
			@Override
			public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("record").as(boolean.class), true)) ;
				//未分配
				list.add(cb.equal(root.get("qualitydistype").as(String.class), UKDataContext.QualityDisStatusType.DISORGAN.toString())) ;
				//权限控制
				In<Object> inOrgan = cb.in(root.get("qualitydisorgan"));
				if(organList.size() > 0){
					for(String id : organList){
						inOrgan.value(id) ;
					}
				}else{
					inOrgan.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(inOrgan) ;
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));  
			}}) ;
		return list;
	}
	public static List<WorkOrders> getOrganDisnotWorkorders(User user){
		List<String> organList = CallCenterUtils.getExistOrgan(user);
		WorkOrdersRepository workOrdersRes = UKDataContext.getContext().getBean(WorkOrdersRepository.class);
		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
		boolQueryBuilder.must(QueryBuilders.termQuery("qualitydistype" , UKDataContext.QualityDisStatusType.DISORGAN.toString()));
		//权限控制
		BoolQueryBuilder bool = new BoolQueryBuilder();
		if(organList.size() > 0) {
			for(String id : organList) {
				bool.should(QueryBuilders.termQuery("qualitydisorgan" , id));
			}
		}else {
			bool.should(QueryBuilders.termQuery("qualitydisorgan" , UKDataContext.UKEFU_SYSTEM_NO_DAT));
		}
		if(bool != null) {
			boolQueryBuilder.must(bool);
		}
		List<WorkOrders> list = workOrdersRes.findByOrgiAndQualitydisorgan(boolQueryBuilder);
		return list;
	}
	public static List<AgentService> getOrganDisnotAgent(User user){
		final String orgi = user.getOrgi();
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		AgentServiceRepository agentServiceRes = UKDataContext.getContext().getBean(AgentServiceRepository.class);
		List<AgentService> list = agentServiceRes.findAll(new Specification<AgentService>(){
			@Override
			public Predicate toPredicate(Root<AgentService> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("qualitydistype").as(String.class), UKDataContext.QualityDisStatusType.DISORGAN.toString())) ;
				//权限控制
				In<Object> inOrgan = cb.in(root.get("qualitydisorgan"));
				if(organList.size() > 0){
					for(String id : organList){
						inOrgan.value(id) ;
					}
				}else{
					inOrgan.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(inOrgan) ;
				
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));   
			}
		}) ;
		return list;
	}
	
	public static void autoQualityStatusEvent(StatusEvent statusEvent) throws IOException {
		System.out.println("自动质检");
		if (statusEvent != null && !StringUtils.isBlank(statusEvent.getId())) {
			QualityMissionHisRepository qualityMissionHisRes = UKDataContext.getContext().getBean(QualityMissionHisRepository.class);		
			QualityTemplateRepository qualityTemplateRes = UKDataContext.getContext().getBean(QualityTemplateRepository.class);		
			QualityTemplateItemRepository qualityTemplateItemRes = UKDataContext.getContext().getBean(QualityTemplateItemRepository.class);		
			QualityResultItemRepository qualityResultItemRes = UKDataContext.getContext().getBean(QualityResultItemRepository.class);		
			QualityResultRepository qualityResultRes = UKDataContext.getContext().getBean(QualityResultRepository.class);		
			VoiceTranscriptionRepository voiceTranscriptionRes = UKDataContext.getContext().getBean(VoiceTranscriptionRepository.class);
			if (!StringUtils.isBlank(statusEvent.getQualityactid()) && !StringUtils.isBlank(statusEvent.getTemplateid())) {
				QualityTemplate qualitytemplate = qualityTemplateRes.findByIdAndOrgi(statusEvent.getTemplateid(), UKDataContext.SYSTEM_ORGI) ; 
				int totalscore = 0;
				boolean isPass = false;
				StringBuilder content = new StringBuilder();
				List<VoiceTranscription> voiceTranscriptionList = voiceTranscriptionRes.findByCallidAndOrgi(statusEvent.getId(), UKDataContext.SYSTEM_ORGI);
				if (voiceTranscriptionList != null && voiceTranscriptionList.size() > 0) {
					for(VoiceTranscription voiceTranscription : voiceTranscriptionList) {
						if (!StringUtils.isBlank(voiceTranscription.getOnebest())) {
							content.append(voiceTranscription.getOnebest());
						}
					}
				}
				QualityMissionHis qualityMissionHis = null;
				List<QualityMissionHis> qualityMissionHisList = qualityMissionHisRes.findByDataidAndOrgi(statusEvent.getId(), UKDataContext.SYSTEM_ORGI) ;
				if (qualityMissionHisList!=null && qualityMissionHisList.size()>0) {
					qualityMissionHis = qualityMissionHisList.get(0);
				}
				if (qualitytemplate != null && qualityMissionHis != null) {
					if (!StringUtils.isBlank(content.toString())) {
						boolean taboo = false;
						List<QualityTemplateItem> qualityTemplateItemList = qualityTemplateItemRes.findByTemplateidAndOrgi(statusEvent.getTemplateid(), UKDataContext.SYSTEM_ORGI) ;
						List<QualityResultItem> qualityResultItemList = new ArrayList<QualityResultItem>() ;
						QualityResult qcresult = new QualityResult() ;
						
						/**
						 * 检验禁忌项
						 */
						if (qualityTemplateItemList!=null && qualityTemplateItemList.size()>0) {
							for(QualityTemplateItem tItem : qualityTemplateItemList){
								if (tItem.getType().equals(UKDataContext.QcTemplateItemType.TABOO.toString())) {
									QualityResultItem ritem = new QualityResultItem();
									if (!StringUtils.isBlank(tItem.getWordstype())) {
										String[] tabooresults = DicSegment.parsebyLibkeys("taboo"+tItem.getWordstype(), content.toString());
										if (tabooresults != null && tabooresults.length >0) {
											ritem.setScore(1);
											taboo = true;
										}
									}
									ritem.setCreater(statusEvent.getQualitydisuser());
									ritem.setCreatetime(new Date());
									ritem.setName(tItem.getName());
									ritem.setOrgi(UKDataContext.SYSTEM_ORGI);
									ritem.setScheme(tItem.getScheme());
									ritem.setType(tItem.getType());
									ritem.setItemid(tItem.getId());
									ritem.setParentid(tItem.getParentid());
									ritem.setResultid(qcresult.getId());
									qualityResultItemList.add(ritem) ;
								}
							}
						}
						
						/**
						 * 检验质检项
						 */
						if (qualityTemplateItemList!=null && qualityTemplateItemList.size()>0) {
							for(QualityTemplateItem tItem : qualityTemplateItemList){
								if (!tItem.getType().equals(UKDataContext.QcTemplateItemType.TABOO.toString()) && tItem.getParentid().equals("0")) {//1级
									//
									QualityResultItem ritem = new QualityResultItem();
									int fenshu1 = 0;
									for(QualityTemplateItem tItem2 : qualityTemplateItemList){
										if (!tItem2.getParentid().equals("0") && tItem2.getParentid().equals(tItem.getId())) {//2级
											QualityResultItem ritem2 = new QualityResultItem();
											boolean hasp = false;
											int fenshu2 = 0;
											for(QualityTemplateItem tItem3 : qualityTemplateItemList){
												if (!tItem3.getParentid().equals("0") && tItem3.getParentid().equals(tItem2.getId())) {//3级
													hasp = true;
													QualityResultItem ritem3 = new QualityResultItem();
													if (!taboo) {
														if (!StringUtils.isBlank(tItem3.getNcontain())) {
															String[] ncontains = tItem3.getNcontain().split("[, ，:；;\\n\t\\r ]");
															if (ncontains != null && ncontains.length > 0) {
																for(String nword : ncontains) {
																	if (content.toString().contains(nword)) {
																		ritem3.setScore(tItem3.getMinscore());
																		fenshu2 += tItem3.getMinscore();
																		break;
																	}
																}
															}
														}
														if (!StringUtils.isBlank(tItem3.getMcontain()) && ritem3.getScore()==0) {
															String[] mcontains = tItem3.getMcontain().split("[, ，:；;\\n\t\\r ]");
															if (mcontains != null && mcontains.length > 0) {
																for(String mword : mcontains) {
																	if (content.toString().contains(mword)) {
																		ritem3.setScore(tItem3.getMaxscore());
																		fenshu2 += tItem3.getMaxscore();
																		break;
																	}
																}
															}
														}
													}
													if (ritem3.getScore()==0) {
														ritem3.setScore(tItem3.getMinscore());
													}
													ritem3.setCreater(statusEvent.getQualitydisuser());
													ritem3.setCreatetime(new Date());
													ritem3.setMaxscore(tItem3.getMaxscore());
													ritem3.setMinscore(tItem3.getMinscore());
													ritem3.setName(tItem3.getName());
													ritem3.setOrgi(UKDataContext.SYSTEM_ORGI);
													ritem3.setScheme(tItem3.getScheme());
													ritem3.setType(tItem3.getType());
													ritem3.setItemid(tItem3.getId());
													ritem3.setParentid(tItem3.getParentid());
													ritem3.setResultid(qcresult.getId());
													qualityResultItemList.add(ritem3) ;
												}
											}
											ritem2.setScore(fenshu2);
											
											if (!hasp) {
												if (!taboo) {
													if (!StringUtils.isBlank(tItem2.getNcontain())) {
														String[] ncontains = tItem2.getNcontain().split("[, ，:；;\\n\t\\r ]");
														if (ncontains != null && ncontains.length > 0) {
															for(String nword : ncontains) {
																if (content.toString().contains(nword)) {
																	ritem2.setScore(tItem2.getMinscore());
																	fenshu1 += tItem2.getMinscore();
																	break;
																}
															}
														}
													}
													if (!StringUtils.isBlank(tItem2.getMcontain()) && ritem2.getScore()==0) {
														String[] mcontains = tItem2.getMcontain().split("[, ，:；;\\n\t\\r ]");
														if (mcontains != null && mcontains.length > 0) {
															for(String mword : mcontains) {
																if (content.toString().contains(mword)) {
																	ritem2.setScore(tItem2.getMaxscore());
																	fenshu1 += tItem2.getMaxscore();
																	break;
																}
															}
														}
													}
												}
												if (ritem2.getScore()==0) {
													ritem2.setScore(tItem2.getMinscore());
												}
											}
											fenshu1 += ritem2.getScore();
											
											ritem2.setCreater(statusEvent.getQualitydisuser());
											ritem2.setCreatetime(new Date());
											ritem2.setMaxscore(tItem2.getMaxscore());
											ritem2.setMinscore(tItem2.getMinscore());
											ritem2.setName(tItem2.getName());
											ritem2.setOrgi(UKDataContext.SYSTEM_ORGI);
											ritem2.setScheme(tItem2.getScheme());
											ritem2.setType(tItem2.getType());
											ritem2.setItemid(tItem2.getId());
											ritem2.setParentid(tItem2.getParentid());
											ritem2.setResultid(qcresult.getId());
											qualityResultItemList.add(ritem2) ;
										}
									}
									///
									totalscore += fenshu1 ;
									ritem.setScore(fenshu1);
									ritem.setCreater(statusEvent.getQualitydisuser());
									ritem.setCreatetime(new Date());
									ritem.setMaxscore(tItem.getMaxscore());
									ritem.setMinscore(tItem.getMinscore());
									ritem.setName(tItem.getName());
									ritem.setOrgi(UKDataContext.SYSTEM_ORGI);
									ritem.setScheme(tItem.getScheme());
									ritem.setType(tItem.getType());
									ritem.setItemid(tItem.getId());
									ritem.setParentid(tItem.getParentid());
									ritem.setResultid(qcresult.getId());
									qualityResultItemList.add(ritem) ;
								}
							}
						}
						
						/**
						 * 得出质检结果
						 */
						if (taboo) {
							totalscore = 0;
						}else {
							if (UKDataContext.QcTemplateItemType.MINUS.toString().equals(qualitytemplate.getArithmetic())) {
								totalscore = qualitytemplate.getTotalscore()-totalscore ;
							}
						}
						if (qualitytemplate.getPassscore()<=totalscore) {
							isPass = true ;
						}
						qcresult.setCreater(statusEvent.getQualitydisuser());
						qcresult.setCreatetime(new Date());
						qcresult.setArithmetic(qualitytemplate.getArithmetic());
//								qcresult.setAdcom(qcFormFilterRequest.getAdcom());
//								qcresult.setImcom(qcFormFilterRequest.getImcom());
//								qcresult.setQacom(qcFormFilterRequest.getQacom());
//								qcresult.setRemarks(qcFormFilterRequest.getRemarks()) ;
						qcresult.setDataid(statusEvent.getId());
						qcresult.setOrgi(UKDataContext.SYSTEM_ORGI);
						qcresult.setTotalscore(qualitytemplate.getTotalscore());
						qcresult.setPassscore(qualitytemplate.getPassscore());
						qcresult.setScore(totalscore);
						qcresult.setQualityuser(statusEvent.getQualitydisuser());
						qcresult.setStatus(UKDataContext.QualityStatus.DONE.toString());
						qcresult.setQualitytype(qualitytemplate.getType());
						qcresult.setIsadcom(qualitytemplate.isIsadcom());
						qcresult.setIsimcom(qualitytemplate.isIsimcom());
						qcresult.setIsitemdir(qualitytemplate.isIsitemdir());
						qcresult.setIsitemrmk(qualitytemplate.isIsitemrmk());
						qcresult.setIsqacom(qualitytemplate.isIsqacom());
						qcresult.setIsrmk(qualitytemplate.isIsrmk());
						qcresult.setIsvp(qualitytemplate.isIsvp());
						qualityResultRes.save(qcresult) ;
						
						if (qualityResultItemList != null && qualityResultItemList.size() > 0) {
							qualityResultItemRes.save(qualityResultItemList) ;
						}
						qualityMissionHis.setQualityscore(totalscore);
						qualityMissionHis.setQualitypass(isPass? 1 : 0);
						qualityMissionHis.setQualitystatus(UKDataContext.QualityStatus.DONE.toString());
						statusEvent.setQualityscore(totalscore);
						statusEvent.setQualitystatus(UKDataContext.QualityStatus.DONE.toString());
						statusEvent.setQualitypass(isPass? 1 : 0);
					}else {
						qualityMissionHis.setQualitystatus(UKDataContext.QualityStatus.DISABLE.toString());
						statusEvent.setQualitystatus( UKDataContext.QualityStatus.DISABLE.toString());
					}
					statusEvent.setQualitytime(new Date());
					statusEvent.setQualityorgan(statusEvent.getQualitydisorgan());
					statusEvent.setQualityuser(statusEvent.getQualitydisuser());
					qualityMissionHis.setQualitytime(new Date());
					qualityMissionHis.setQualitytype(qualitytemplate.getType());
					qualityMissionHis.setQualityuser(statusEvent.getQualitydisuser());
					qualityMissionHis.setQualityorgan(statusEvent.getQualitydisorgan());
					qualityMissionHisRes.save(qualityMissionHis) ;
				}
			}
		}
	}
}
